/**
 * 描述：
 * Copyright：Copyright （c） 2017
 * Company：南京银行
 * 
 * @author njcbkf045
 * @version 1.0 2017年4月21日
 * @see history
 *      2017年4月21日
 */

package com.njcb.ams.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.njcb.ams.util.AmsAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.njcb.ams.repository.dao.AuthROrgResoDao;
import com.njcb.ams.repository.entity.AuthROrgReso;
import com.njcb.ams.repository.entity.AuthROrgResoExample;
import com.njcb.ams.pojo.dto.Tree;
import com.njcb.ams.factory.domain.AppContext;
import com.njcb.ams.util.TreeNodeUtil;

/**
 * @author njcbkf045
 *
 *         类功能描述：
 *
 */
@Service
public class AuthROrgResoService {

	@Autowired
	private AuthROrgResoDao authROrgResoDao;
	@Autowired
	private ResourceManageService resourceManageService;

	public static AuthROrgResoService getInstance() {
		return AppContext.getBean(AuthROrgResoService.class);
	}

	/**
	 * 方法功能描述：
	 * 
	 * @param orgId
	 */

	public List<AuthROrgReso> getResobyOrg(int orgId) {
		List<AuthROrgReso> orgResos = new ArrayList<AuthROrgReso>();
		AuthROrgResoExample example = new AuthROrgResoExample();
		AuthROrgResoExample.Criteria criteria = example.createCriteria();
		if (orgId != 0) {
			criteria = criteria.andOrgIdEqualTo(orgId);
			orgResos = authROrgResoDao.selectByExample(example);
		}

		return orgResos;
	}

	public List<Tree> orgResoQuery(int orgId) {

		// 获取所有权限
		List<Tree> trees = new ArrayList<Tree>();
		List<Tree> treeList = resourceManageService.selectAllMenu();

		// 获取角色对应的权限ID
		List<AuthROrgReso> authROrgResos = this.getResobyOrg(orgId);

		// 修改权限树对应的checked状态
		// tree_id是reso_id，关联表的主键作为树的一个属性
		for (AuthROrgReso rr : authROrgResos) {
			int resID = rr.getResId().intValue();
			for (Tree tree : treeList) {
				int treeid = tree.getId();
				if (treeid == resID) {
					tree.setChecked("true");
					Map<String, Object> attributes = new HashMap<String, Object>();
					attributes.put("keyID", rr.getId());
					tree.setAttributes(attributes);
				}
			}
		}

		// 改变树的形式，便于页面展示
		trees = TreeNodeUtil.getTierTrees(treeList);
		return trees;

	}

	/**
	 * 方法功能描述：
	 * 
	 * @param deleteNodes
	 */
	public void orgResoSave(List<AuthROrgReso> insertNodes, List<AuthROrgReso> deleteNodes) {

		for (AuthROrgReso rr : insertNodes) {
			AmsAssert.notNull(rr.getOrgId(),rr.getResId(),"orgId和resId不完整");
			authROrgResoDao.insert(rr);
		}

		for (AuthROrgReso rr : deleteNodes) {
			authROrgResoDao.deleteByPrimaryKey(rr.getId());
		}

	}
}
